package org.code.boot.controller.boot;

import java.util.List;
import java.util.Set;
import java.util.HashSet;

import org.code.boot.domain.boot.BizTrain;
import org.code.boot.service.boot.IBizTrainService;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.Map;
import java.util.Collections;
import cn.hutool.core.collection.CollUtil;
import org.code.boot.common.utils.CollectionUtils;
import org.code.boot.common.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.code.boot.common.annotation.Log;
import org.code.boot.common.enums.BusinessType;
import org.code.boot.controller.BaseController;
import org.code.boot.vo.AjaxResult;
import org.code.boot.domain.boot.BizMealOrder;
import org.code.boot.service.boot.IBizMealOrderService;
import org.code.boot.vo.TableDataInfo;
import org.code.boot.domain.system.SysUser;
import org.code.boot.service.system.ISysUserService;
import org.code.boot.domain.boot.BizTrainMeal;
import org.code.boot.service.boot.IBizTrainMealService;
import org.code.boot.domain.boot.BizTrainOrder;
import org.code.boot.service.boot.IBizTrainOrderService;

/**
 * 火车餐订单Controller
 * 
 * @author coder
 * @date 2025-08-28
 */
@RestController
@RequestMapping("/boot/mealorder")
public class BizMealOrderController extends BaseController
{
    @Autowired
    private IBizMealOrderService bizMealOrderService;

    @Autowired
    private ISysUserService sysuserService;

    @Autowired
    private IBizTrainMealService biztrainmealService;

    @Autowired
    private IBizTrainOrderService bizTrainOrderService;
    @Autowired
    private IBizTrainService biztrainService;
    /**
     * 查询火车餐订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BizMealOrder bizMealOrder)
    {
        startPage();
        List<BizMealOrder> list = bizMealOrderService.selectBizMealOrderList(bizMealOrder);
        list = buildDetailList(list);
        return getDataTable(list);
    }



    /**
     * 获取火车餐订单下拉选项列表
     */
    @GetMapping("/options")
    public AjaxResult getOptions()
    {
        List<BizMealOrder> list = bizMealOrderService.selectBizMealOrderList(new BizMealOrder());
        return success(list);
    }

    /**
     * 获取当前用户的火车票订单列表
     */
    @GetMapping("/userTrainOrders")
    public AjaxResult getUserTrainOrders()
    {
        BizTrainOrder queryParam = new BizTrainOrder();
        queryParam.setUserId(getUserId());
        List<BizTrainOrder> list = bizTrainOrderService.selectBizTrainOrderList(queryParam);
        return success(list);
    }

    /**
     * 根据用户ID获取火车票订单列表
     */
    @GetMapping("/trainOrdersByUserId/{userId}")
    public AjaxResult getTrainOrdersByUserId(@PathVariable("userId") Long userId)
    {
        BizTrainOrder queryParam = new BizTrainOrder();
        queryParam.setUserId(userId);
        List<BizTrainOrder> list = bizTrainOrderService.selectBizTrainOrderList(queryParam);
        return success(list);
    }

    /**
     * 获取当前用户的餐食订单列表
     */
    @GetMapping("/userOrders")
    public AjaxResult getUserMealOrders()
    {
        BizMealOrder queryParam = new BizMealOrder();
        queryParam.setUserId(getUserId());
        List<BizMealOrder> list = bizMealOrderService.selectBizMealOrderList(queryParam);
        list = buildDetailList(list);
        return success(list);
    }

    /**
     * 获取火车餐订单详细信息
     */
    @GetMapping(value = "/{mealOrderId}")
    public AjaxResult getInfo(@PathVariable("mealOrderId") Long mealOrderId)
    {
        return success(bizMealOrderService.selectBizMealOrderByMealOrderId(mealOrderId));
    }

    /**
     * 新增火车餐订单
     */
    @Log(title = "火车餐订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizMealOrder bizMealOrder)
    {
        bizMealOrder.setCreateBy(getNickname());
        return toAjax(bizMealOrderService.insertBizMealOrder(bizMealOrder));
    }

    /**
     * 修改火车餐订单
     */
    @Log(title = "火车餐订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizMealOrder bizMealOrder)
    {
        bizMealOrder.setUpdateBy(getNickname());
        return toAjax(bizMealOrderService.updateBizMealOrder(bizMealOrder));
    }

    /**
     * 删除火车餐订单
     */
    @Log(title = "火车餐订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{mealOrderIds}")
    public AjaxResult remove(@PathVariable Long[] mealOrderIds)
    {
        return toAjax(bizMealOrderService.deleteBizMealOrderByMealOrderIds(mealOrderIds));
    }

    /**
     * 构建详细信息列表
     * 
     * @param list 列表数据
     * @return 构建后的列表数据
     */
    private List<BizMealOrder> buildDetailList(List<BizMealOrder> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        
        // 获取用户Map
        Map<Long, SysUser> userIdMap = sysuserService.getSysUserMap(
                CollectionUtils.convertSet(list, BizMealOrder::getUserId));
        
        // 获取餐食Map
        Map<Long, BizTrainMeal> mealIdMap = biztrainmealService.getBizTrainMealMap(
                CollectionUtils.convertSet(list, BizMealOrder::getMealId));
        
        // 获取火车票订单Map
        Map<Long, BizTrainOrder> trainOrderIdMap = bizTrainOrderService.getBizTrainOrderMap(
                CollectionUtils.convertSet(list, BizMealOrder::getTrainOrderId));
        
        // 获取火车票订单关联的火车ID集合
        Set<Long> trainIds = new HashSet<>();
        trainOrderIdMap.values().forEach(trainOrder -> {
            if (trainOrder.getTrainId() != null) {
                trainIds.add(trainOrder.getTrainId());
            }
        });
        
        // 获取火车信息Map
        Map<Long, BizTrain> trainIdMap = biztrainService.getBizTrainMap(trainIds);
        
        // 拼接结果
        list.forEach(item -> {
            // 拼接用户名称
            MapUtils.findAndThen(userIdMap, item.getUserId(), 
                userIdItem -> item.setUserIdName(userIdItem.getNickName()));
            // 拼接餐食名称
            MapUtils.findAndThen(mealIdMap, item.getMealId(), 
                mealIdItem -> item.setMealIdName(mealIdItem.getMealName()));
            // 拼接火车票订单信息
            MapUtils.findAndThen(trainOrderIdMap, item.getTrainOrderId(), 
                trainOrderItem -> {
                    // 获取火车信息来获取车次号
                    MapUtils.findAndThen(trainIdMap, trainOrderItem.getTrainId(), 
                        trainItem -> {
                            String trainNumber = trainItem.getTrainNumber();
                            item.setTrainOrderIdName("车次: " + trainNumber + "(" + trainOrderItem.getSeatNumber() + ",订单号:" + trainOrderItem.getTrainOrderId() + ")");
                        });
                });
        });
        
        return list;
    }
}
